import React, { useMemo, useState } from 'react';
import { history, connect } from 'umi';
import _ from 'lodash';
import SearchInput from './SearchInput';
import { getOriginalPath } from '@/utils/routeFormat';

// 菜单搜索高亮
const MenuSearchItem = ({ labels, searchKey }) => {
  const labelIndex = _.findIndex(labels, (item) => item.indexOf(searchKey) > -1);
  if (labelIndex > -1) {
    const beforeLabels = labels.slice(0, labelIndex);
    const afterLabels = labels.slice(labelIndex + 1);
    const textIndex = labels[labelIndex].indexOf(searchKey);
    const beforeStr = labels[labelIndex].substr(0, textIndex);
    const afterStr = labels[labelIndex].substr(textIndex + searchKey.length);
    return (
      <span>
        {beforeLabels.join(' >> ')}
        {!!beforeLabels.length && ' >> '}
        {beforeStr}
        <span className="system-header-right-container-menu-search-active-text">{searchKey}</span>
        {afterStr}
        {!!afterLabels.length && ' >> '}
        {afterLabels.join(' >> ')}
      </span>
    );
  }
  return <span>{labels.join(' >> ')}</span>;
};

export default connect(({ menu }) => ({
  routePathList: menu.routePathList,
}))(({ routePathList }) => {
  // state数据
  const [searchKey, setSearchKey] = useState('');
  const [searchResults, setSearchResults] = useState([]);

  // 可搜索的菜单项
  const getMenuSearchOptions = (routePath) => {
    const searchOptions = [];
    _.forEach(_.values(routePath), (list) => {
      if (list.length) {
        const { path } = list.slice(-1)[0];
        if (path) {
          searchOptions.push({
            path,
            labels: _.map(list, 'name'),
          });
        }
      }
    });
    return searchOptions;
  };
  const menuSearchOptions = useMemo(() => getMenuSearchOptions(routePathList), [routePathList]);

  // 菜单搜索
  const searchMenuList = (val) => {
    setSearchKey(val);
    if (val) {
      const resultList = _.filter(
        menuSearchOptions,
        (item) => !!_.filter(item.labels, (label) => label.indexOf(val) > -1).length,
      );
      setSearchResults(resultList);
    }
  };

  // 菜单选择
  const selectMenuResult = (path) => {
    setSearchKey('');
    setSearchResults([]);
    if (getOriginalPath(history.location?.pathname) !== path) {
      history.push(path);
    }
  };

  return (
    <SearchInput
      className="system-header-right-container-menu-search"
      placeholder="菜单搜索"
      defaultValue=""
      onChange={searchMenuList}
      onSelect={selectMenuResult}
      options={searchResults.map((item) => ({
        label: <MenuSearchItem {...item} searchKey={searchKey} />,
        value: item.path,
        text: _.last(item.labels),
      }))}
    />
  );
});
